package com.bsj.pay.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.bsj.pay.config.GlobalConfig;
import com.bsj.pay.dao.IpPoolDao;
import com.bsj.pay.model.IpPoolBean;
import com.bsj.pay.service.IpPoolService;
import com.bsj.pay.util.date.DateTimeUtil;
import com.bsj.pay.util.http.Http;
import com.bsj.pay.util.http.Http.Response;
import com.bsj.pay.util.http.HttpProxy;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class IpPoolServiceImpl implements IpPoolService {
	private static final Logger logger = LogManager.getLogger(IpPoolServiceImpl.class);
	
	public static Map<String, Long> getIpType = new HashMap<String, Long>();
	
	@Autowired
	private IpPoolDao dao;
	
	public long insert(IpPoolBean t) {
		return this.dao.insert(t);
	}

	public int deleteById(Long id) {
		return this.dao.deleteById(id);
	}

	public List<IpPoolBean> queryList(IpPoolBean t) {
		return this.dao.queryList(t);
	}

	public int update(IpPoolBean t) {
		return this.dao.update(t);
	}

	public IpPoolBean getById(Long Id) {
		return (IpPoolBean) this.dao.getById(Id);
	}

	public long count(IpPoolBean t) {
		return this.dao.count(t);
	}

	public PageInfo<IpPoolBean> pageList(IpPoolBean t, int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		List<IpPoolBean> list = this.dao.queryList(t);
		PageInfo<IpPoolBean> pageInfo = new PageInfo(list);
		return pageInfo;
	}

	public int removeById(Long id) {
		return 0;
	}

	public List<IpPoolBean> queryAll() {
		return null;
	}

	public void UpdateIpPoolTask() throws Exception {
		if(OrderServiceImpl.lastActiveTime<System.currentTimeMillis()/1000-600)
		{
			return;
		}
		int expiredCount = this.dao.removeExpired();
		if(expiredCount>0)logger.info("删除过期ip：" + expiredCount);
		long ipcount=this.dao.count(null);
		if (ipcount> 2) {
			return;
		}
		List<HttpProxy> ipList = getNewProxy();
		if (ipList == null|| (ipList.size() == 0)) {
			logger.info("未获取到代理ip");
			return;
		}
		int insertCont = 0;
		for (HttpProxy httpProxy : ipList) {
			try {
				IpPoolBean insertModel = new IpPoolBean();
				insertModel.setIp(httpProxy.getHost());
				if (this.dao.count(insertModel) > 0) {
					continue;
				}
				insertModel.setPort(httpProxy.getPort());
				insertModel.setExpire_time(httpProxy.getExpire_time());
				insertModel.setCity(httpProxy.getCity());
				this.dao.insert(insertModel);
				insertCont++;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		logger.info("新增" + insertCont + "条代理IP");
	}
	
	public static Stack<HttpProxy> getNewProxy(String url) {
		if(StringUtils.isEmpty(url)) {
			return null;
		}
		Stack<HttpProxy> stack = new Stack<HttpProxy>();
		try {
			Response res = Http.create(url).get().send().getResponse();
			if (res.getStatus() == 0 || StringUtils.isEmpty(res.getResult())) {
				return null;
			}
			logger.info("获取代理IP结果：" + res.getResult());
			JSONObject json = JSONObject.fromObject(res.getResult());
			if ((json.getInt("code") == 200) || (json.getInt("code") == 0)) {
				JSONArray array = json.getJSONArray("data");
				for (int i = 0; i < array.size(); i++) {
					JSONObject ipDate = array.getJSONObject(i);
					try {
						String proxyIp = ipDate.containsKey("ip") ? ipDate.getString("ip") : ipDate.optString("IP");
						int proxyPort = ipDate.containsKey("port") ? Integer.parseInt(ipDate.getString("port"))
								: ipDate.getInt("Port");
						long expire_time = System.currentTimeMillis() / 1000 + 120;
						if (ipDate.containsKey("expire_time")) {
							expire_time = DateTimeUtil.strDate2UnixTime(ipDate.getString("expire_time"));
						} else if (ipDate.containsKey("ExpireTime")) {
							expire_time = DateTimeUtil.strDate2UnixTime(ipDate.getString("ExpireTime"));
						}
						String city=ipDate.optString("city", null);
						HttpProxy proxy = new HttpProxy(proxyIp, proxyPort);
						proxy.setExpire_time(expire_time);
						proxy.setCity(city);
						stack.push(proxy);
					} catch (Exception e) {
						return null;
					}
				}
				return stack;
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public List<HttpProxy> getNewProxy() {
		String proxy_url = GlobalConfig.proxy_url;
		if (StringUtils.isEmpty(proxy_url)) {
			return null;
		}
		List<HttpProxy> ipList = new ArrayList();
		try {
			Response res = Http.create(proxy_url).get().send().getResponse();
			if (StringUtils.isEmpty(res.getResult())) {
				return null;
			}
			logger.info("获取代理IP结果：" + res.getResult());
			JSONObject json = JSONObject.fromObject(res.getResult());
			if ((json.getInt("code") == 200) || (json.getInt("code") == 0)) {
				JSONArray array = json.getJSONArray("data");
				for (int i = 0; i < array.size(); i++) {
					JSONObject ipDate = array.getJSONObject(i);
					try {
						String proxyIp = ipDate.containsKey("ip") ? ipDate.getString("ip") : ipDate.optString("IP");
						int proxyPort = ipDate.containsKey("port") ? Integer.parseInt(ipDate.getString("port"))
								: ipDate.getInt("Port");
						long expire_time = System.currentTimeMillis() / 1000 + 120;
						if (ipDate.containsKey("expire_time")) {
							expire_time = DateTimeUtil.strDate2UnixTime(ipDate.getString("expire_time"));
						} else if (ipDate.containsKey("ExpireTime")) {
							expire_time = DateTimeUtil.strDate2UnixTime(ipDate.getString("ExpireTime"));
						}
						String city=ipDate.optString("city", null);
						HttpProxy proxy = new HttpProxy(proxyIp, proxyPort);
						proxy.setExpire_time(expire_time);
						proxy.setCity(city);
						ipList.add(proxy);
					} catch (Exception e) {
						return null;
					}
				}
				return ipList;
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public synchronized IpPoolBean getOneCanUseIp() {
		IpPoolBean ipPool = this.dao.getOneCanUseIp();
		if (ipPool != null) {
			this.dao.removeById(ipPool.getId());
		}
		return ipPool;
	}
}
